package com.merugu.school.util;

import javax.el.ELContext;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 * Utility class for JSF related operations
 */
public class JsfUtil {

    /**
     * Adds an error message to faces context
     *
     * @param clientId client id of the components
     * @param msg     Message
     */

    public static void addErrorMessage(String clientId, String msg) {
        addMessage(clientId, msg, FacesMessage.SEVERITY_ERROR);
    }

    /**
     * Adds message to the faces context
     *
     * @param clientId Client id to which the message to be added
     * @param msg      the message
     * @param severity Severity  of the message
     */
    private static void addMessage(String clientId, String msg, FacesMessage.Severity severity) {
      FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(severity, msg, msg));
    }

    /**
     * Returns the bean instance by given name
     *
     * @param beanName the bean identifier
     * @param clazz    The required type
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <T> T findManagedBean(String beanName, Class<T> clazz) {
       FacesContext jsf = FacesContext.getCurrentInstance();
        ELContext elContext = jsf.getELContext();
        Object bean = elContext.getELResolver().getValue(elContext, null, beanName);
        if (clazz.isAssignableFrom(bean.getClass())) {
            return (T) bean;
        }
        return null;
    }
}
